package com.allin.mall.common.core.handler;

import com.allin.mall.common.core.api.CommonResult;
import com.allin.mall.common.core.api.ResultCodeEnum;
import com.allin.mall.common.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.reactive.resource.NoResourceFoundException;

/**
 * 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public CommonResult exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return CommonResult.fail(ResultCodeEnum.SYSTEM_ERROR);
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(value = NoResourceFoundException.class)
    public CommonResult notFoundHandler(Exception e) {
        return CommonResult.fail(ResultCodeEnum.NOT_FOUND);
    }

    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public CommonResult businessException(BusinessException e) {
        return CommonResult.fail(e.getCode());
    }
}
